import React from 'react'
import { Icon, Modal } from 'antd'
import { STATE } from '@/const'
import { useRequest } from 'ahooks'
import { requestWrapper } from '@/utils/request'
import newAPI from '@/services/new'
import './styles.scss'
import iacFormat from '@/utils/format'
const { confirm } = Modal
export default function Item(props) {
    const {
        desc,
        state,
        newsImg,
        title,
        readCount,
        id,
        history,
        createAt,
        isAdmin,
        userName,
        getNewList = () => {}
    } = props
    const { run: deleteNew } = useRequest(
        newId =>
            requestWrapper(newAPI.delete.bind(null, newId), {
                autoSuccess: true,
                successMessage: '删除新闻成功！'
            }),
        {
            formatResult: data => data || [],
            manual: true,
            onSuccess: () => {
                getNewList()
            }
        }
    )

    const toUpdate = newId => {
        if (isAdmin) {
            props.history.push({
                pathname: '/news/new-content',
                search: `?newId=${newId}`,
                state: { newId: newId }
            })
        } else {
            history.push({
                pathname: '/news/update-new',
                search: `?newId=${newId}`,
                state: { newId: newId }
            })
        }
    }

    const confirmDel = id => {
        confirm({
            title: '你确定要删除该新闻吗?',
            content: '当你删除该新闻之后将无法找回！',
            okText: '确定删除',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                deleteNew(id)
            },
            onCancel() {}
        })
    }

    return (
        <div className='card'>
            <div className='header' onClick={() => toUpdate(id)}>
                <img src={newsImg ? newsImg : '/assets/dog.jpg'} alt='' />
                <div>
                    <h3 title={title}>{title}</h3>
                    <p>{desc}</p>
                </div>
            </div>
            {isAdmin || (
                <div
                    className='myDel'
                    onClick={() => {
                        confirmDel(id)
                    }}>
                    <Icon type='close' />
                </div>
            )}
            <div className='item_footer'>
                {isAdmin ? (
                    <>
                        <Icon type='user' /> <span>{userName}</span>
                    </>
                ) : (
                    <>
                        <Icon type='read' /> <span>{readCount}</span>
                    </>
                )}
                <Icon type='alert' /> <span>{STATE[state]}</span>
                <Icon type='dashboard' /> <span>{iacFormat(createAt)}</span>
            </div>
        </div>
    )
}
